package com.panda.pfs.web;

import com.panda.pfs.utils.FileUtil;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

@Controller
public class TestController {

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public String saveFile(ServletRequest servletRequest,
                         ServletResponse servletResponse,
                         @RequestParam("key") String key,
                         @RequestParam("file") MultipartFile file,
                         @RequestParam("suffix") String suffix) throws IOException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String uuid = UUID.randomUUID().toString();
        File path = new File("/file/" + key + FileUtil.hashPath(uuid));
        if (!path.exists()) {
            path.mkdirs();
        }
        File temp = new File(path.getAbsolutePath() + "/" + uuid + "." + suffix);
        FileOutputStream fileOutputStream = new FileOutputStream(temp);
        IOUtils.copy(file.getInputStream(), fileOutputStream);
        file.getInputStream().close();
        fileOutputStream.close();
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST,OPTIONS,GET,PUT,DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "accept,x-requested-with,Content-Type");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        return uuid + "." + suffix;
    }

    @RequestMapping(value = "/get/{key}/{fileName}", method = RequestMethod.GET)
    public void getFile(ServletRequest servletRequest,
                         ServletResponse servletResponse,
                        @PathVariable("key") String key,
                        @PathVariable("fileName") String fileName) throws IOException {
        File file = new File("/file/" + key + FileUtil.hashPath(FileUtil.withoutSuffixName(fileName)) + fileName);
        FileInputStream fileInputStream = new FileInputStream(file);
        IOUtils.copy(fileInputStream, servletResponse.getOutputStream());
        try {
            fileInputStream.close();
            servletResponse.getOutputStream().close();
        } catch (Exception e) {
        }
    }


}
